package genosAgape.ui.die;

import genosAgape.controle.DieControle;
import genosAgape.ui.DockableFrame;
import genosAgape.ui.MdiGA;
import genosAgape.util.DialogoOcupado;
import genosAgape.vo.Die;

import java.awt.Component;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyVetoException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;


public class Pesquisar extends DockableFrame implements Runnable {
	private JTextField tfCodigo;
	private JTable table;
	private DieControle dies = new DieControle();
	List<Die> diesResult ;
	private ListSelectionModel listSelectDie;
	private JTextField tfNome;
	private DefaultTableModel dftDie;
	private boolean threadAtiva = false;
	private Thread th;
	 
	private static Pesquisar instance;
	
	public static Pesquisar getInstance() throws ParseException, PropertyVetoException{
		if(instance==null){			
			instance = new Pesquisar("Pesquisar",MdiGA.taskBar);
			instance.setVisible(true);
		}
		else if(!instance.isVisible()) {
			try {
				if(instance.isIcon())
					instance.setIcon(false);
				else
					instance.setVisible(true);
			} catch (PropertyVetoException e) {
				e.printStackTrace();
			}
		}		
		return instance;
	}
	
	@Override	
	public void dispose() {
		super.dispose();
		instance = null;			
	}
	
	private Pesquisar(String title, JToolBar jtb) throws PropertyVetoException {
		super(title,jtb);
		setClosable(true);
		setIconifiable(true);
		
		setIcon(new ImageIcon(Editar.class.getResource("/genosAgape/ui/img/icons/search.png")));
		
		setBounds(100, 100, 841, 515);
		dftDie = new DefaultTableModel(null, new String[]{"CODIGO", "NOME", "RG","CPF","NASCIMENTO"});
		table = new JTable();
		table.enableInputMethods(false);
		table.setModel(dftDie);
		listSelectDie = table.getSelectionModel();
		tfNome = new JTextField();
		tfNome.setEditable(true);
		
		JLabel lblNewLabel = new JLabel("Nome:");
		lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		
		tfCodigo = new JTextField();
		tfCodigo.setColumns(10);
		
		JLabel lblNewLabel_1 = new JLabel("Codigo:");
		lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
		
		JScrollPane scrollPane = new JScrollPane();
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 805, Short.MAX_VALUE)
						.addGroup(groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(tfCodigo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNewLabel_1))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(tfNome, GroupLayout.PREFERRED_SIZE, 301, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNewLabel))))
					.addContainerGap())
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.TRAILING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_1)
						.addComponent(lblNewLabel))
					.addGap(3)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(tfCodigo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(tfNome, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(11)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 367, GroupLayout.PREFERRED_SIZE)
					.addGap(124))
		);
		groupLayout.linkSize(SwingConstants.HORIZONTAL, new Component[] {tfNome, lblNewLabel});
		groupLayout.linkSize(SwingConstants.HORIZONTAL, new Component[] {tfCodigo, lblNewLabel_1});
		
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollPane.setViewportView(table);
		table.getColumnModel().getColumn(0).setPreferredWidth(20);
		table.getColumnModel().getColumn(1).setPreferredWidth(280);
		table.getColumnModel().getColumn(2).setPreferredWidth(20);
		getContentPane().setLayout(groupLayout);
		
		addListeners();
	}
	
	private void addListeners(){
		listSelectDie.addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent arg) {
				if(!arg.getValueIsAdjusting()){
					getLinhaSelecionada(table);
					table.clearSelection();
				}
			}
		});
		
		tfCodigo.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent ev) {
				try {
					if(ev.getKeyCode() == 8)
						return;
					
					String[] fields = new String[]{null,null,null,null};
					diesResult = dies.listarDies(Integer.parseInt(tfCodigo.getText().trim()));
					while(dftDie.getRowCount() > 0){
						dftDie.removeRow(0);
					}
					
					int count = diesResult.size();
					SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
					for(int i = 0 ; i < count; i++){
						dftDie.addRow(fields);
						dftDie.setValueAt(diesResult.get(i).getCodigoDistribuido(), i, 0);
						dftDie.setValueAt(diesResult.get(i).getNome(), i, 1);
						dftDie.setValueAt(diesResult.get(i).getRg(), i, 2);
						dftDie.setValueAt(diesResult.get(i).getCpf(), i, 3);
						if(diesResult.get(i).getDataDeNascimento()!=null)
							dftDie.setValueAt(formato.format(diesResult.get(i).getDataDeNascimento()), i, 4);
					}					
						
				}catch(NumberFormatException e){
					JOptionPane.showMessageDialog(null, "Entrada invalida.\n"+"Digite Apenas Numero " +
							"neste campo","Erro",JOptionPane.ERROR_MESSAGE);
					tfCodigo.setText("");
				}catch (Exception e) {
					JOptionPane.showMessageDialog(null, "Erro ao consultar Die!\n"+e.getMessage()
							,"Erro",JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		
		tfNome.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent ev) {
				if(tfNome.getText().length() < 3)
					return;
				if(ev.getKeyCode() == 8)
					return;
				try {
					start();
				} catch (Exception e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "Erro ao consultar Die!\n"+e.getMessage()
							,"Erro",JOptionPane.ERROR_MESSAGE);
				}
			}
		});
	}
	
	private void criarLinha(){
		try {
			String[] fields = new String[]{null,null,null,null};
			diesResult = dies.listarDies(tfNome.getText().trim());
		while(dftDie.getRowCount() > 0){
			dftDie.removeRow(0);
		}
		int count = diesResult.size();
		SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
		for(int i = 0 ; i < count; i++){
			dftDie.addRow(fields);
			dftDie.setValueAt(diesResult.get(i).getCodigoDistribuido(), i, 0);
			dftDie.setValueAt(diesResult.get(i).getNome(), i, 1);
			dftDie.setValueAt(diesResult.get(i).getRg(), i, 2);
			dftDie.setValueAt(diesResult.get(i).getCpf(), i, 3);
			if(diesResult.get(i).getDataDeNascimento()!=null)
				dftDie.setValueAt(formato.format(diesResult.get(i).getDataDeNascimento()), i, 4);
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		try {
			if (!threadAtiva) {
				threadAtiva = true;
				Thread.sleep(200);
				dftDie.setNumRows(0);
				criarLinha();
			} else {
				threadAtiva = false;
				th.interrupt();
				this.start();
			}
		} catch (InterruptedException e) {}
	}
	
	public void start(){
		if(th == null){
			th = new Thread(this);
			th.start();
		}else{
			new Thread(this).start();
		}
	}
	
	private void getLinhaSelecionada(JTable tb) {
		if(tb.getSelectedRow() != -1){
			try {
				DialogoOcupado dialogo = new DialogoOcupado("Aguarde...");;
				dialogo.abrirDialogo();
				Editar frameEditar = Editar.getInstance();
				frameEditar.setDieView(diesResult.get(tb.getSelectedRow()));
				if(frameEditar.getParent() != MdiGA.areaTrabalho)
					MdiGA.areaTrabalho.add(frameEditar);
				frameEditar.setSelected(true);
				dialogo.fecharDialogo();
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (PropertyVetoException e) {
				e.printStackTrace();
			}				
		}
	}
}
